import { AnimationClip, Sprite, SpriteFrame, animation } from "cc";
import ResourceManager from "../Runtime/ResourceManager";
import StateMachine from "./StateMachine";
import { sortSpriteFrame } from "../utils";

export const ANIMATION_STEP = 1/8

export default class State {
  private animationClip:AnimationClip
  run() {
    if (this.fsm.animationComponent?.defaultClip?.name === this.animationClip.name) {
      return
    }
    this.fsm.animationComponent.defaultClip = this.animationClip
    this.fsm.animationComponent.play()
  }
  constructor(private fsm:StateMachine,
    private path: string,
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
    private speed = ANIMATION_STEP) {
    this.init()
  }

  async init() {
    const promise = ResourceManager.Instance.loadDir(this.path)
    this.fsm.waitingList.push(promise)
    const spriteFrames = await promise

    this.animationClip = new AnimationClip()

    const track = new animation.ObjectTrack()
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame')
    const frames: Array<[number, SpriteFrame]> = sortSpriteFrame(spriteFrames).map((item, index) => [this.speed * index, item])
    track.channel.curve.assignSorted(frames)

    this.animationClip.addTrack(track)
    this.animationClip.name = this.path
    this.animationClip.duration = frames.length * this.speed
    this.animationClip.wrapMode = this.wrapMode
  }
}
